package com.example.tsproject.Controller;

import com.example.tsproject.Utils.ThreadLocalUtil;
import com.example.tsproject.entity.CommentWithStudent;
import com.example.tsproject.entity.Comments;
import com.example.tsproject.entity.Result;
import com.example.tsproject.entity.Students;
import com.example.tsproject.service.CommentsService;
import com.example.tsproject.service.StudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: t-s-project
 * @BelongsPackage: com.example.tsproject.Controller
 * @Author: YoungDra
 * @CreateTime: 2025/03/06  16:41
 */
@RestController
@RequestMapping("/comments")
public class CommentController {

    @Autowired
    private CommentsService commentsService;
    @Autowired
    private StudentsService studentsService;

    // Add a new comment
    @PostMapping
    public Result addComment(@RequestBody Comments comment) {
        String stu_number= ThreadLocalUtil.get();
        Students students=studentsService.findStudents(stu_number);
        System.out.println("*********************");
        System.out.println(students);
        comment.setStudent_id(students.getId());
        comment.setComment_time(new Date());
        System.out.println(comment);
        boolean isSaved = commentsService.save(comment);
        if (isSaved) {
            return Result.success("Comment added successfully");
        } else {
            return Result.error("Failed to add comment");
        }
    }

    // Get all comments for a specific post
    @GetMapping("/post/{postId}")
    public Result getCommentsByPostId(@PathVariable Integer postId) {
        List<CommentWithStudent> comments = commentsService.getCommentsByPostId(postId);
        if (comments != null) {
            return Result.success(comments);
        } else {
            return Result.error("No comments found for this post");
        }
    }
}
